package com.example.springsecurity.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springsecurity.pojo.LoginUser;
import com.example.springsecurity.pojo.SysUser;
import com.example.springsecurity.service.SysUserService;
import com.example.springsecurity.mapper.SysUserMapper;
import com.example.springsecurity.utils.JwtUtil;
import com.example.springsecurity.utils.RedisCache;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.sql.Time;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
* @author 10352
* @description 针对表【sys_user(用户表)】的数据库操作Service实现
* @createDate 2023-02-01 15:24:05
*/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService{

    @Autowired
        private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public String login(SysUser sysUser) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(sysUser.getUserName(),sysUser.getPassword());

        Authentication authentication = authenticationManager.authenticate(authenticationToken);

        if (Objects.isNull(authentication)){
            throw new RuntimeException("账号或密码错误");
        }
        //存到Redis里面去
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        //登录成功，创建一个token卡，也就是个身份，
        String token = JwtUtil.createJWT(loginUser.getSysUser().getId().toString());


        //登录的时候存到缓存里面去
        //定时
        redisCache.setCacheObject("login:"+loginUser.getSysUser().getId(),loginUser,1, TimeUnit.HOURS);
        return token;


    }

    @Override
    public void logout() {
        //拿到当前用户
        LoginUser loginUser = (LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //删除
        redisCache.getCacheObject("login:"+loginUser.getSysUser().getId());
    }
}




